﻿using System;
using System.Globalization;
using System.Windows.Forms;
using SF.Code.Extension.DebuggingHelper;
using SF.Code.Extension.WinAPI;
using SG.Ling.AutoTranslator.NLP;

namespace SG.Ling.AutoTranslator.Translation
{
    partial class UserForm
    {
        private System.Drawing.Icon _normalTaskbarIcon;
        private System.Drawing.Icon _activeTaskbarIcon;
        private void SetupTaskbarIcons()
        {
            _normalTaskbarIcon = Properties.Resources.translator_auto_clip;
            _activeTaskbarIcon = Properties.Resources.translator_active;
        }

        private void BatchTranslatorErrorOccurred(object sender, object obj)
        {
            var exception = obj as Exception;

            var component = (sender ?? this).GetType().FullName;
            if (exception == null)
                "Translation failed for unknown reason".PrintToDebugger(component);
            else
                exception.Log(category: component);
        }

        public BatchTranslator SystemTranslator { get { return batchTranslatorSystem; } }

        private TranslationTuple _lastTranslation;
        private void BatchTranslatorTranslationCompleted(object sender, TranslationTuple tuple, bool fromCache)
        {
            _lastTranslation = tuple;
            InvokeOrDirect(() => DisplayTranslation(tuple, fromCache));
        }

        private void TranslateButtonClick(object sender, EventArgs e)
        {
            if (_tbEdit != null)
                TranslateAsync(new ClipboardTextChangedEventArgs(_tbEdit.Text));
        }

        public void TranslateAsync(ClipboardTextChangedEventArgs e)
        {
            TranslateAsync(e.Text);
        }
        public void TranslateAsync(string text)
        {
            Func<ComboBox, CultureInfo> getSelectedCulture = pBox => pBox.SelectedItem as CultureInfoDisplay;

            var source = text.NormalizeInput();
            if (string.IsNullOrEmpty(source) || IsAlreadyTranslated(source))
                return;

            _tbEdit.Text = source;

            var queued = batchTranslatorUser.TranslateAsync(source, sourceLanguage: getSelectedCulture(comboBoxSource),
                                                            targetLanguage: getSelectedCulture(comboBoxTarget));

            if (queued)
                _tbEdit.Text = source;
        }

        private bool IsAlreadyTranslated(string source)
        {
            return _lastTranslation != null && _lastTranslation.EqualsAny(source) && _tbEdit.TextLength > 0 &&
                   _tbTranslated.TextLength > 0;
        }

        private void DisplayTranslation(TranslationTuple tuple, bool fromCache)
        {
            speakControl1.CurrentTranslation = tuple;

            CopyTranslationToClipboard(tuple);

            DisplayTextWithTransliteration(_tbTranslated, tuple.TargetText, tuple.TargetTransliteration);
            DisplayTextWithTransliteration(_tbEdit, tuple.SourceText, tuple.SourceTransliteration);

            UpdateHits(fromCache);

            DisplayHitRatio();
        }

        private void CopyTranslationToClipboard(TranslationTuple tuple)
        {
            if (!autoClipboardToolStripMenuItem.Checked)
                return;

            timerResetNotifyIcon.Stop();

            notifyIconTaskbar.Icon = _activeTaskbarIcon;

            Clipboard.SetText(tuple.TargetText, TextDataFormat.UnicodeText);

            timerResetNotifyIcon.Start();
        }

        private void UpdateHits(bool fromCache)
        {
            if (_settings == null) return;

            if (fromCache)
                _settings.Hits++;
            else
                _settings.Misses++;
        }

        private void DisplayHitRatio()
        {
            if (_settings == null)
                return;

            var total = _settings.Hits + _settings.Misses;
            if (total > 0)
                labelHitRatioValue.Text = string.Format("{0:0.00} %", 100.0*((double) _settings.Hits/total));
        }

        private static void DisplayTextWithTransliteration(TextBoxBase textBox, string text, string transliteration)
        {
            if (string.IsNullOrWhiteSpace(text)) return;
            textBox.Text = text;

            if (string.IsNullOrWhiteSpace(transliteration)) return;
            textBox.AppendText("\r\n[");
            textBox.AppendText(transliteration);
            textBox.AppendText("]");
        }

    }
}
